package org.example.service;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.*;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class TestServiceImpl implements TestService {

    // 测试工作流的进程ID
    private final static String ProcessInstanceByKey = "testProcess";

    @Autowired
    RuntimeService runtimeService;

    @Autowired
    TaskService taskService;

    @Autowired
    HistoryService historyService;

    @Override
    public String test1() {
        String name = "Zhang San";
        log.info("name:======={}", name);
        return name;
    }

    @Override
    public String test2() {
        String name = "Zhang San";
        log.info("name:======={}", name);
        log.info("method startActivityDemo 开始....");
        Map<String, Object> map = new HashMap<>();
        map.put("apply", "zhangsan");
        map.put("approve", "lisi");
        // 创建流程引擎
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();

        // 获取流程存储服务组件
        RepositoryService repositoryService = processEngine.getRepositoryService();

        // 获取运行时服务组件
        RuntimeService runtimeService = processEngine.getRuntimeService();

        // 获取流程任务组件
        TaskService taskService = processEngine.getTaskService();

        // 1、部署流程文件
        repositoryService.createDeployment().name("myProcess")
                .addClasspathResource("processes/demo.bpmn").deploy();
        //流程启动
        // ExecutionEntity pi1 = (ExecutionEntity) runtimeService.startProcessInstanceByKey("leave",map);
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("demo", map);
        // String processId = pi1.getId();
        String processId = processInstance.getId();
//		String taskId = pi1.getTasks().get(0).getId();
        String taskId = taskService.createTaskQuery().processInstanceId(processId).singleResult().getId();
        taskService.complete(taskId, map);//完成第一步申请
        Task task = taskService.createTaskQuery().processInstanceId(processId).singleResult();
        String taskId2 = task.getId();
        map.put("pass", false);
        taskService.complete(taskId2, map);//驳回申请
        log.info("method startActivityDemo startProcessInstanceByKey结束....");
        return name;
    }

    @Override
    public String startProcess() {
        Map<String, Object> map = new HashMap<>(16);
        // 启动一个流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(ProcessInstanceByKey, map);
        log.info("processInstance.getId()======={}", processInstance.getId());
        return processInstance.getId() + " success";
    }

    @Override
    public String queryCurrentTask(String processInstanceId) {
        // 查询当前实例对应的任务进度(singleResult单条，list多条)
        List<Task> tasks = taskService.createTaskQuery().processInstanceId(processInstanceId).list();
        List<String> ids = new ArrayList<>();
        log.info("tasks：==========={}", tasks);
        if (tasks != null && !tasks.isEmpty()) {
            tasks.forEach(task -> {
                log.info("任务ID======={}", task.getId());
                log.info("任务NAME======={}", task.getName());
                log.info("实例ID======={}", task.getProcessInstanceId());
                log.info("s分配对象======={}", task.getAssignee());
            });
            ids = tasks.stream().map(Task::getId).collect(Collectors.toList());
        } else {
            log.info("当前实例不存在任务！");
        }
        return "当前任务ID=======" + ids;
    }

    @Override
    public String salesReview(String taskId) {
        Map<String, Object> map = new HashMap<>(16);
        // 销售经理审核确认
        taskService.complete(taskId, map);
        return "销售经理审核success";
    }

    @Override
    public String financeReview(String taskId) {
        Map<String, Object> map = new HashMap<>(16);
        // 销售经理审核确认
        taskService.complete(taskId, map);
        return "财务经理审核success";
    }

    @Override
    public List<HistoricActivityInstance> queryHistoryActivity(String processInstanceId) {
        // 查询实例的历史流程(按时间顺序排序)
        List<HistoricActivityInstance> historyList = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricActivityInstanceStartTime()
                .asc()
                .list();
        log.info("historyActivityList:=========={}", historyList);
        return historyList;
    }

    @Override
    public List<HistoricTaskInstance> queryHistoryTask(String processInstanceId) {
        // 查询任务的历史流程(按时间顺序排序)
        List<HistoricTaskInstance> historyList = historyService.createHistoricTaskInstanceQuery()
                .processInstanceId(processInstanceId)
                .orderByHistoricTaskInstanceStartTime()
                .asc()
                .list();
        log.info("historyTaskList:=========={}", historyList);
        return historyList;
    }

}
